
Import-Module -Name E:\Src\powershell\config.psm1 

function String-Contains {
    param (
        [String]
        $OriginString,
        [array]
        $SubStringArray
    )
    foreach ($item in $SubStringArray) {
        if ($OriginString.Contains($item)) {
            return $true
        }
    }
    return $false
}

function Get-NatAppURL {
    $url = "Failed to Get URL"
    $time = 0
    while ($true -and ($time -le 100)) {
        Start-Sleep -Milliseconds 100
        $log = ""
        if (Test-Path $natAppLogPath) {
            $log = Get-Content $natAppLogPath
            if ($log) {
                $log | ForEach-Object {
                    if ($_ -match $parttern) {
                        $url = $Matches[0]
                        break
                    }
                }
            }
        }
        $time += 1
    }
    return $url
}

$taskList = @(
    # job of mysqld
    'mysqld.exe --console',
    # nginx
    'nginx.exe -p "$env:NGINX_HOME"',
    # php-cgi
    'php-cgi.exe -b 127.0.0.1:9000',
    # redis
    "redis-server.exe $redisConfigPath",
    # natapp 
    "natapp.exe -authtoken=$authtoken -log $natAppLogPath -loglevel INFO"
)

$parttern = "\bhttp://[A-Z0-9._%+-]+\.natappfree\.cc\b"

if ($args.Count -ge 1) {
    switch ($args[0]) {
        "start" {
            $_error = $false
            $scoopPath = "$env:SCOOP/shims"
            $scoopGlobalPath = "$env:SCOOP_GLOBAL/shims"
            $taskList | ForEach-Object {
                $app = $_.Split(' ')[0]
                if ((-not (Test-Path "$scoopPath/$app")) -and (-not (Test-Path "$scoopGlobalPath/$app"))) {
                    Write-Host "
                Application $($app.Replace('.exe', '').Replace('mysqld','mysql').Replace('-server','')) not install, type " -ForegroundColor Red -NoNewline
                    Write-Host "scoop install $($app.Replace('.exe', '').Replace('mysqld','mysql').Replace('-server',''))"-ForegroundColor Blue -NoNewline
                    Write-Host " to install it." -ForegroundColor Red
                    $_error = $true
                }
            }
            if ($_error) {
                Write-Host "
                Please make sure that you have downloaded all the application, then use this script to start your web service." -ForegroundColor Yellow
                break
            }
            if (Test-Path $natAppLogPath) {
                Remove-Item $natAppLogPath
            }
            Write-Host {
                Now try to start all the web service, please wait...
            } -ForegroundColor Yellow
            foreach ($task in $taskList) {
                $sb = [scriptblock]::Create("$task")
                Start-Job -ScriptBlock $sb -Name $task.Split(' ')[0].Replace('.exe', '').Replace('-server', '').Replace('mysqld', 'mysql')
            }
            Write-Host {
                Keep the powershell process running.
                Once you shut down the powershell process, all the service will be downed.

                Now wait for Natapp response... } -ForegroundColor Yellow
            $url = Get-NatAppURL
            Write-Host "
                Your NatApp URL is : " -NoNewline -ForegroundColor Yellow
            Write-Host $url -ForegroundColor Blue
        }
        "stop" {
            Write-Host {
                Now try to stop all the web service, please wait... } -ForegroundColor Yellow

            if ((Get-Job).Count -eq 0) {
                Write-Host "
                Oh no, no service was started..." -ForegroundColor Yellow
            }
            else {
                Get-Job | ForEach-Object {
                    if (String-Contains $_.Command.ToString() $taskList) {
                        Stop-Job $_.Id
                        Remove-Job $_.Id
                        Write-Host "
                service $($_.Command.Split(' ')[0].Replace('.exe', '').Replace('mysqld','mysql').Replace('-server','')) has been closed..." -ForegroundColor Yellow
                        if ($_.Command.Contains('natapp.exe')) {
                            if (Test-Path $natAppLogPath) {
                                Remove-Item $natAppLogPath
                            }
                        }
                    }
                }
            }
            Write-Host {
                Done it!
            } -ForegroundColor Blue
        }
        "php-fpm" {
            Write-Host "
                We need to shutdown the service php-cgi then use simple FastGCI Process Manager to manage the php-cgi process..." -ForegroundColor Yellow
            Get-Job | ForEach-Object {
                if ($_.Command.ToString().Contains("php-cgi.exe")) {
                    Stop-Job $_.Id
                    Remove-Job $_.Id
                }
            }
            $count = 1
            if ($args.Count -eq 2) {
                if (($args[1].GetType() -eq [System.Int32])) {
                    if ($args[1] -ge 1) {
                        $count = $args[1]
                    }
                    else {
                        Write-Host "
                Wrong number provided...
                Use default setting..." -ForegroundColor Red
                    }
                }
                else {
                    Write-Host "
                Wrong type provided...
                Use default setting..." -ForegroundColor Red
                }
            }
            Write-Host "
                Now we start the fpm...
                Set the process count to "-NoNewline -ForegroundColor Yellow
            Write-Host $count -ForegroundColor Blue -NoNewline
            Write-Host " ..." -ForegroundColor Yellow
            $sb = [scriptblock]::Create("while(`$true){for(`$_count = 0;`$_count -lt $count;`$_count++){Start-Job -ScriptBlock {php-cgi.exe -b 127.0.0.1:9000} -Name 'php-cgi'};Get-Job | Wait-Job;Get-Job | Remove-Job;}")
            Write-Host $sb
            Start-Job -ScriptBlock $sb -Name 'php-fpm'
        }
        "show" {
            if ($args.Count -eq 1) {
                Write-Host "`t`tName`t`tState`n`t`t----`t`t----"
                Get-Job | ForEach-Object {
                    if (String-Contains $_.Command.ToString() $taskList) {
                        Write-Host "`t`t$($_.Name.Split(' ')[0].Replace('.exe', '').Replace('-server', '').Replace('mysqld','mysql'))`t`t$($_.State.ToString())" -ForegroundColor Yellow
                    }
                }
            }
            if ($args.Count -eq 2) {
                switch ($args[1]) {
                    "url" { 
                        $url = Get-NatAppURL
                        Write-Host "
                Your NatApp URL is : " -NoNewline -ForegroundColor Yellow
                        Write-Host $url -ForegroundColor Blue
                        Write-Host
                    }
                }
            }
        }
        Default {
            Write-Host "Unknown Operation"
        }
    }
}
else {
    Write-Host "Lack of operation"
}